<script lang="ts" setup>
import type {
  GridInstance as VxeGridInstance,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';

import { computed, onMounted, ref } from 'vue';

import { Button, Form, Input, message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getXhsListApi } from '#/api/core/xhs';

// 表格引用
const gridRef = ref<VxeGridInstance>();

// 存储表格数据
const tableData = ref<XhsApi.XhsInfo[]>([]);

// 添加分页相关的 ref
const currentPage = ref(1);
const totalPage = ref(0);

// 表格配置
const gridOptions = computed<VxeGridProps<XhsApi.XhsInfo>>(() => ({
  columns: [
    { field: 'id', title: 'ID' },
    { field: 'at_xhs_user', title: '用户名' },
    { field: 'key_word', title: '赛道' },
    {
      field: 'create_time',
      title: '创建时间',
      width: 180,
      formatter: ({ cellValue }) => {
        if (!cellValue) return '';
        return new Date(cellValue).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false,
        });
      },
    },
  ],
  data: tableData.value,
  pagerConfig: {
    enabled: true,
    pageSize: 10,
    total: totalPage.value * 10,
    currentPage: currentPage.value,
    layouts: ['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Total'],
    perfect: true,
  },
  sortConfig: {
    multiple: true,
  },
}));

const gridEvents: VxeGridListeners<XhsApi.XhsInfo> = {
  // 点击效果
  pageChange: ({ currentPage: newPage }) => {
    currentPage.value = newPage;
    loadData();
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  gridOptions: gridOptions.value,
});

// 定义搜索表单的数据结构
interface SearchForm {
  username: string;
  key_word: string;
}

// 搜索表单数据
const searchForm = ref<SearchForm>({
  username: '',
  key_word: '',
});

// 修改加载数据方法
async function loadData() {
  try {
    gridApi.setLoading(true);
    const params: XhsApi.XhsListParams = {
      current_page: currentPage.value,
      username: searchForm.value.username,
      key_word: searchForm.value.key_word,
    };

    const response = await getXhsListApi(params);

    if (Array.isArray(response)) {
      tableData.value = response;
      const total_page = response[0]?.total_page || 0;
      totalPage.value = total_page;

      gridApi.setGridOptions({
        data: tableData.value,
        pagerConfig: {
          ...gridOptions.value.pagerConfig,
          total: total_page * 10,
          currentPage: currentPage.value,
        },
      });
    } else {
      message.error('获取数据格式错误');
      tableData.value = [];
    }
  } catch {
    message.error('获取列表失败');
    tableData.value = [];
  } finally {
    gridApi.setLoading(false);
  }
}

// 修改搜索方法
function handleSearch() {
  currentPage.value = 1; // 搜索时重置到第一页
  loadData();
}

// 修改重置方法
function handleReset() {
  currentPage.value = 1; // 重置时回到第一页
  searchForm.value = {
    username: '',
    key_word: '',
  };
  loadData();
}

onMounted(() => {
  loadData();
});

// 表格显示控制
const showBorder = gridApi.useStore((state) => state.gridOptions?.border);
const showStripe = gridApi.useStore((state) => state.gridOptions?.stripe);

function changeBorder() {
  gridApi.setGridOptions({
    border: !showBorder.value,
  });
}

function changeStripe() {
  gridApi.setGridOptions({
    stripe: !showStripe.value,
  });
}
</script>

<template>
  <div class="p-4">
    <!-- 添加搜索表单 -->
    <Form class="mb-4" layout="inline">
      <Form.Item label="用户名">
        <Input
          v-model:value="searchForm.username"
          allow-clear
          placeholder="请输入用户名"
        />
      </Form.Item>
      <Form.Item label="赛道">
        <Input
          v-model:value="searchForm.key_word"
          allow-clear
          placeholder="请输入赛道"
        />
      </Form.Item>
      <Form.Item>
        <Button class="mr-2" type="primary" @click="handleSearch">搜索</Button>
        <Button @click="handleReset">重置</Button>
      </Form.Item>
    </Form>

    <div class="vp-raw w-full">
      <Grid ref="gridRef">
        <template #toolbar-tools>
          <Button class="mr-2" type="primary" @click="changeBorder">
            {{ showBorder ? '隐藏' : '显示' }}边框
          </Button>
          <Button class="mr-2" type="primary" @click="changeStripe">
            {{ showStripe ? '隐藏' : '显示' }}斑马纹
          </Button>
        </template>
      </Grid>
    </div>
  </div>
</template>
